<template>
  <div id="touchSetting">
    <div class="table-conBtn">
      <el-switch
        v-model="reachValue"
        inactive-text="是否发送消息"
        active-color="#1dc8a4"
        inactive-color="#ccc"
        :disabled="!canEdit"
      >
      </el-switch>
    </div>
    <div class="table-conBtn">
      <el-button
        v-if="reachValue"
        type="warning"
        icon="el-icon-plus"
        :disabled="!canEdit"
        @click="addEditRoles('add')"
      >
        创建触达
      </el-button>
    </div>
    <!-- 表格部分-->
    <el-table v-if="reachValue" :data="tableData" style="width: 100%">
      <el-table-column type="index" width="60" align="center" label="序号">
      </el-table-column>
      <el-table-column
        prop="reachsUserName"
        label="触达用户"
        min-width="150"
      ></el-table-column>
      <el-table-column
        prop="touchTime"
        label="发布时间"
        min-width="160"
      ></el-table-column>
      <el-table-column prop="touchType" label="触达渠道">
        <template slot-scope="{ row }">
          {{ filterTouchType(row.touchType) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template slot-scope="{ row, $index }">
          <el-button
            type="text"
            :disabled="!canEdit"
            @click="addEditRoles('edit', row, $index)"
          >
            编辑
          </el-button>
          <el-button
            type="text"
            :disabled="!canEdit"
            @click="deleteReach(row.reachId, $index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="showBtn" class="btn-box">
      <el-button plain @click="cancelLabel">
        取 消
      </el-button>
      <el-button
        type="success"
        :loading="loading"
        @click="confirmLabel('ruleForm')"
      >
        保存
      </el-button>
      <el-button type="primary" @click="nextLab('userRule')">
        上一步
      </el-button>
      <el-button type="primary" @click="nextLab('prizeSetting')">
        下一步
      </el-button>
    </div>
    <!-- 新增/编辑角色dialog -->
    <dialogAddEdit
      v-if="dialogData.isShow"
      :dialog-data="dialogData"
      @addSubList="addSubList"
      @editSubList="editSubList"
      @refresh="refresh"
    ></dialogAddEdit>
  </div>
</template>

<script>
import {
  saveActivities,
  saveTouchList,
  delTouchList
} from '@/api/activeManagement/templatePage' // 接口
import dialogAddEdit from '@component/activeManagement/common/touchSettiong/dialogAddEdit' //创建触达
import { clearTagMixins } from '@/mixins/clearTag'

export default {
  name: 'touchSetting',
  msg: '触达设置',
  mixins: [clearTagMixins],
  components: {
    dialogAddEdit
  },
  props: [
    'type',
    'touchSettingList',
    'userRulList',
    'subData',
    'backPage',
    'id'
  ],
  data() {
    return {
      reachValue: true, // 是否发送消息
      loading: false,
      tableData: [], //列表
      subList: [], //要提交的内容
      dialogData: {
        isShow: false, // 默认隐藏
        type: 'add', // 默认新增
        params: '', // 编辑时，传递的参数
        i: -1, //下标
        preeListAdd: [] //预设用户规则列表，添加到触达用户列表后面
      },
      typeList: {
        BOMB_SCREEN: '弹屏',
        NOTICE: '通知',
        SMS: '短信',
        PUSH: '推送'
      },
      canEdit: true,
      isSave: false //是否保存
    }
  },
  computed: {
    showBtn() {
      //是否显示保存按钮
      return this.type === 'add' || this.type === 'edit'
    }
  },
  watch: {
    touchSettingList(newV, oldV) {
      this.tableData = this.touchSettingList.concat(this.subList)
    },
    reachValue(newV, oldV) {
      if (newV === false) {
        this.subList = []
        this.tableData = [...this.touchSettingList]
      }
    },
    subData(newV) {
      if (newV.activityAuditing) {
        this.getCanEdit()
      }
      this.reachValue = newV.reachs.status
    },
    userRulList(newV) {
      if (newV.length > 0) {
        this.getPreeListAdd()
      }
    }
  },
  mounted() {
    this.tableData = [...this.touchSettingList]
  },
  methods: {
    getCanEdit() {
      this.canEdit =
        (this.type === 'add' || this.type === 'edit') &&
        this.subData.activityAuditing.twoAuditing.auditingState !== 'PASS'
    },
    resetIsSave() {
      this.isSave = false
    },
    //根据触达渠道英文返回中文
    filterTouchType(type) {
      return this.typeList[type] || ''
    },
    /*获取添加到“触达用户列表”后面的“用户规则列表”*/
    getPreeListAdd() {
      let ary = []
      this.userRulList.forEach((item) => {
        ary.push({
          preestablishCrowdId: item.id,
          reachsUserName: item.name
        })
        this.dialogData.preeListAdd = [...ary]
      })
    },
    // 新增/编辑
    addEditRoles(type, row = {}, i = -1) {
      this.dialogData.type = type === 'add' ? true : false
      this.dialogData.id = row.reachId || ''
      if (!this.dialogData.type && !this.dialogData.id) {
        //没有提交保存的数据进行编辑
        let { displayTerminals } = row
        this.dialogData.params = { ...row }
        //数组转字符串
        this.dialogData.params.displayTerminals = displayTerminals[0] || ''
        this.dialogData.i = i
      }
      this.dialogData.isShow = true
    },
    /*新增要提交的数据*/
    addSubList(obj) {
      let curItem = { ...obj }
      //字符串转数组
      curItem.displayTerminals = curItem.displayTerminals
        ? [curItem.displayTerminals]
        : []
      curItem.preestablishCrowdId = obj.touchUser.preestablishCrowdId
      curItem.reachsUserName = obj.touchUser.reachsUserName
      delete curItem.touchUser
      this.subList.push(curItem)
      this.tableData.push(curItem)
    },
    /*编辑未保存的数据*/
    editSubList({ obj, i }) {
      let curItem = { ...obj }
      //字符串转数组
      curItem.displayTerminals = curItem.displayTerminals
        ? [curItem.displayTerminals]
        : []
      curItem.preestablishCrowdId = obj.touchUser.preestablishCrowdId
      curItem.reachsUserName = obj.touchUser.reachsUserName
      delete curItem.touchUser
      //删除未提交数据
      let listLength = this.tableData.length - this.subList.length
      let subIndex = i - listLength
      this.tableData.splice(i, 1, curItem)
      this.subList.splice(subIndex, 1, curItem)
    },
    /*取消*/
    cancelLabel() {
      let _this = this
      if (this.isSave) {
        this.clearTag()
      } else {
        this.$confirm(
          '您的信息尚未保存，取消后所填写的信息将不被保存，确定要退出？',
          '提示',
          {
            distinguishCancelAndClose: true,
            confirmButtonText: '保存后退出',
            cancelButtonText: '直接退出',
            type: 'warning'
          }
        )
          .then(() => {
            Promise.all([_this.saveList(), _this.saveSwitch()]).then(() => {
              _this.isSave = true
              _this.clearTag()
            })
          })
          .catch((action) => {
            if (action === 'cancel') {
              this.clearTag()
            }
          })
      }
    },
    /*退出*/
    signOut() {
      this.$router.go(-1)
      // let query = {
      //   mId: this.$route.query.mId
      // }
      // this.$router.replace({ name: this.backPage, query: query })
    },
    //删除
    deleteReach(rid, i) {
      let _this = this
      this.$confirm('确定要删除该触达吗?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          if (rid) {
            //删除已提交数据
            delTouchList(
              this.id,
              rid,
              (response) => {
                this.$emit('getTouchSettingList')
              },
              (response) => {
                this.$message.warning(response.message)
              }
            )
          } else {
            //删除未提交数据
            let listLength = _this.tableData.length - _this.subList.length
            let subIndex = i - listLength
            this.tableData.splice(i, 1)
            this.subList.splice(subIndex, 1)
          }
        })
        .catch(() => {})
    },
    /*保存*/
    confirmLabel(formName) {
      let _this = this
      Promise.all([_this.saveList(), _this.saveSwitch()]).then(() => {
        _this.isSave = true
      })
    },
    /*保存列表*/
    saveList() {
      return new Promise((resolve, reject) => {
        this.loading = true
        let obj = [...this.subList]
        saveTouchList(
          this.id,
          obj,
          (response) => {
            this.loading = false
            this.$emit('getTouchSettingList')
            this.subList = []
            resolve(true)
          },
          (response) => {
            this.loading = false
            this.$message.warning(response.message)
            reject()
          }
        )
      })
    },
    /*保存switch*/
    saveSwitch() {
      return new Promise((resolve, reject) => {
        let reachs = { status: this.reachValue }
        saveActivities(
          this.id,
          { reachs },
          (response) => {
            resolve(true)
          },
          (response) => {
            this.$message.warning(response.message)
            reject()
          }
        )
      })
    },
    /*下一步*/
    nextLab(labName) {
      let _this = this
      Promise.all([_this.saveList(), _this.saveSwitch()]).then(() => {
        _this.$emit('changeLab', labName)
      })
    },
    /*刷新列表*/
    refresh() {
      this.$emit('getTouchSettingList')
    }
  }
}
</script>

<style lang="less">
#touchSetting {
  .btn-box {
    padding-top: 30px !important;
  }
}
</style>
